import axios from 'axios'
import JSBridge from './JSBridge'
import './Authorization'

let YSModule = {}
const jsBridge = JSBridge.getInstance()

YSModule.install = function (Vue, options) {
  Vue.config.productionTip = false
  Vue.prototype.axios = axios
  Vue.prototype.jsBridge = jsBridge
  Vue.prototype.domain = 'http://' + window.location.host + '/#/'

  Vue.prototype.pushWeblink = function (link) {
    console.log(link)
    let weblink = jsBridge.resolveLink(link)
    console.log(weblink)
    if (weblink) {
      const loading = this.$toast.loading({
        mask: true,
        duration: 0,
        position: 'middle',
        className: 'toast-loading',
        forbidClick: true
      })
      new Promise((resolve, reject) => {
        jsBridge.pushWeb(weblink, res => {
          return resolve(res)
        })
      }).then(res => {
        loading.clear()
        if (process.env.NODE_ENV === 'development') {
          console.log(res)
          this.$router.push({
            name: res.name,
            params: res.property
          })
        }
      })
    } else {
      this.$toast('跳转类型错误')
    }
  }

  Vue.prototype.pushNativelink = function (data) {
    if (!data) {
      return
    }
    new Promise((resolve, reject) => {
      jsBridge.callNativeHandler(data, res => {
        return resolve(res)
      })
    }).then(res => {
      console.log(res)
      console.log(data)
      if (!res) {
        return
      }
      if (!res.status) {
        this.$router.replace({
          name: 'error',
          params: res
        })
      } else {
        if (process.env.NODE_ENV === 'development') {
          if (data.scheme) {
            console.log(data.data)
            this.$router.push({
              name: data.name,
              params: data.data ? data.data : {}
            })
          } else {
            this.$router.push({
              name: 'error',
              params: {
                message: '打开原生功能:' + data.title,
                tip: data.route
              }
            })
          }
        }
      }
    })
  }

  // jsBridge.toast = Vue.toast

  // 给iOS监听请求完成
  jsBridge.finishLoaded(null)
}

export default YSModule
